package com.justreading.order.third.sms;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.justreading.common.utils.R;
import com.justreading.order.constant.SmsConstant;
import com.justreading.order.constant.TokenConstant;
import com.justreading.order.dao.UserDao;
import com.justreading.order.entity.UserEntity;
import com.justreading.order.exception.BizCodeEnum;
import com.justreading.order.utils.RedisUtil;
import com.justreading.order.utils.SmsComponent;
import com.justreading.order.utils.TokenManager;
import com.justreading.order.vo.UserInfoVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author LYJ
 * @Description 生成短信验证码的服务
 * @date 2021 年 02 月 23 日 15:11
 */
@RestController
@RequestMapping("order/third/sms")
public class SmsController {
    @Autowired
    private SmsComponent smsComponent;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private UserDao userDao;

    @Autowired
    private TokenManager tokenManager;

    @Autowired
    private RedisUtil redisUtil;

    @PostMapping("/sendCode")
    public R sendCode(@RequestParam(name = "phone",required = true) String phone) {
        long expire = redisUtil.getExpire(SmsConstant.SMS_PHONE_PRE + phone, TimeUnit.MINUTES);
        if (expire == -2 ||  5 - expire > 1) {  //超过一分钟或者过期重新获取验证码
            Random random = new Random();
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < 4; i++) {
                int num = random.nextInt(9);
                stringBuilder.append(num);
            }
            smsComponent.sendCode(phone, stringBuilder.toString());
            redisUtil.set(SmsConstant.SMS_PHONE_PRE + phone, stringBuilder.toString(), 5, TimeUnit.MINUTES);
        }
        return R.ok();
    }

    /**
     *验证验证码，如果已有用户直接返回用户信息(相当于直接登录)
     * @param code
     * @param phone
     * @return
     */
    @PostMapping("/validCode")
    public R validCode(@RequestParam(name = "code", required = true) String code,
                       @RequestParam(name = "phone", required = true) String phone) {
        String redisCode = (String) redisUtil.get(SmsConstant.SMS_PHONE_PRE + phone);
        if (StringUtils.isNotEmpty(redisCode) && redisCode.equals(code)) {
            UserEntity userEntity = userDao.selectOne(new QueryWrapper<UserEntity>().eq("mobile", phone));
            if(!ObjectUtils.isEmpty(userEntity)){
                UserInfoVo userInfoVo = new UserInfoVo();
                BeanUtils.copyProperties(userEntity,userInfoVo);
                String token = tokenManager.createToken(userEntity.getId().toString());
                userInfoVo.setToken(token);
                redisUtil.set(TokenConstant.TOKEN_USER_ENTITY_PRE + token, userEntity.getId(),30,TimeUnit.DAYS);
                return R.ok().setData(userInfoVo);
            }
            return R.ok();
        } else {
            return R.error(BizCodeEnum.CODE_NOT_MATCH.getCode(), BizCodeEnum.CODE_NOT_MATCH.getMessage());
        }
    }
}
